import axios from 'axios'
import React, {  createContext, useContext, useEffect, useMemo, useReducer, useState } from 'react'
import { useHistory } from 'react-router'
import MainHead from './MainHead'


function SearchBar({tag:Tag}){
    const {state,dispatch} = useContext(SetType)
    const tab = [{tag:'article',name:'文章'},{tag:'user',name:'用户'}]
    // useEffect(()=>{
    //     const bar = document.getElementsByClassName('searchList')[0]
    //     function handleScroll(){
    //         let a = document.documentElement.scrollTop
    //         if(a>100&&top===62)
    //         {
    //             bar.style.transition='all 0.3s'
    //             setTop(0)
    //         }
    //         else if(a<100)
    //         {
    //             bar.style.transition=''
    //             setTop(62)
    //         }
    //     }
    //     window.addEventListener('scroll',handleScroll)
    //     return()=>{
    //         window.removeEventListener('scroll',handleScroll)
    //     }
    // })
    useEffect(()=>{
        const article = document.getElementsByClassName('article')[0]
        // console.log(article)
        const user = document.getElementsByClassName('user')[0]
        const toArticle=()=>{
            dispatch({type:'article'})
        }
        const toUser=()=>{
            dispatch({type:'user'})
        }
        article.addEventListener('click',toArticle)
        user.addEventListener('click',toUser)
        return()=>{
            article.removeEventListener('click',toArticle)
            user.removeEventListener('click',toUser) 
        }
    })
    return(
        <div className='searchTop' style={{height:48,width:'100%',top:62,position:'fixed',fontSize:'14px',lineHeight:'46px',textAlign:'center',display:'flex',zIndex:100,backgroundColor:'#fff'}}>
            {
                tab.map((i,index)=>{

                    return(
                        <div key={index} className={i.tag} style={{width:52,marginLeft:10,color:state.id_type===i.tag?'#007FFF':'#71777C',cursor:'pointer'}}>
                            {i.name}
                        </div>
                    )
                })
            }
            
        </div>
    )
}
function SearchBottom(){
    const {state,dispatch} = useContext(SetType)
    const history =useHistory()
    const [tag] = useState([{tag:'main',name:'主页'},{tag:'hot',name:'热门'},{tag:'new',name:'最新'}])
    useEffect(()=>{
        const hot = document.getElementsByClassName('hotForSearch')[0]
        const newest = document.getElementsByClassName('newForSearch')[0]
        const main = document.getElementsByClassName('mainForSearch')[0]
        const newList = document.getElementsByClassName('searchListForNew')[0]
        const hotList = document.getElementsByClassName('searchListForHot')[0]
        // const user = document.getElementsByClassName('searchListForUser')[0]
        const toHot=()=>{
            dispatch({type:'hot'})
            newList.scrollTop=0
            hotList.scrollTop=0

        }
        const toNew=()=>{
            dispatch({type:'new'})
            newList.scrollTop=0
            hotList.scrollTop=0

        }
        const toMain=()=>{
            history.push('/')
        }
        hot.addEventListener('click',toHot)
        newest.addEventListener('click',toNew)
        main.addEventListener('click',toMain)
        return()=>{
            hot.removeEventListener('click',toHot)
            newest.removeEventListener('click',toNew)
            main.removeEventListener('click',toMain)
        }
    })
    return(
        <div>
            <div className='BottomBar' style={{width:375,height:50,backgroundColor:'#fff',color:'#71777C',zIndex:'200',position:'fixed',bottom:0,display:'flex',justifyContent:'center'}}>
                    {tag.map((i,index)=>{
                        return (
                            <div key={index} className={i.tag+'ForSearch'}>
                                <div className='Box' style={{width:110,display:'flex',cursor:'pointer',justifyContent:'center',alignItems:'center'}}>
                                    <div className='title' style={{textAlign:'center',width:100,lineHeight:'50px',color:i.tag===state.sort_type&&state.id_type==='article'?'#007FFF':'#71777C'}}>
                                        {i.name}
                                    </div>
                                </div>
                            </div>
                        )
                    })}
            </div>
        </div>
    )
}

function SearchArticleBox({brief:props}){

    const info = props.result_model

    let viewSrc = 'https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/img/view.1eda8fa.png'
    let likeSrc = ''
    let commentSrc = ''
    let picSrc = info.article_info.cover_image?info.article_info.cover_image:'https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/934d1d63530b4bddb4d133a8d3d81ef5~tplv-k3u1fbpfcp-zoom-mark-crop-v2:0:0:360:240.awebp'
    let s = new Date(new Date().setHours(0, 0, 0, 0)).getTime()/1000
    let time = Number(info.article_info.ctime)
    let a = s-time
    let date = null
    if(a<3600)  
        date='1小时内'
    else if(a<86400)
        date = (a/3600).toFixed(0)+'小时前'
    else if(a<604800)
        date = (a/86400).toFixed(0)+'天前'
    else if(a<2419200)
        date = (a/604800).toFixed(0)+'周前'
    else if(a<29030400)
        date = (a/2419200).toFixed(0)+'月前'
    else 
        date = (a/29030400).toFixed(0)+'年前'
    return(
        <div>
            <div className='box' style={{width:375,height:141,display:'flex'}} >
                <div className='space' style={{width:20,height:141}}>

                </div>
                <div className='info' style={{width:335,height:141,display:'flex',flexWrap:'wrap'}}>
                    <div className='spaceTop' style={{width:335,height:12}}></div>
                    <div className='userAndTimeAndTag' style={{width:335,height:22,display:'flex',alignItems:'center'}}>
                        <div className='user' style={{fontSize:'13px',height:22,lineHeight:'22px',textAlign:'center',color:'#4e5969'}}>
                            {info.author_user_info?info.author_user_info.user_name:'洛竹'}
                        </div>
                        <div className='space' style={{width:8,borderRight:'1px solid hsla(0,0%,59.2%,.2)',height:14}}>

                        </div>
                        <div className='space' style={{width:7,height:22}}>

                        </div>
                        <div className='time' style={{fontSize:'13px',height:22,lineHeight:'22px',color:'#86909c'}}>
                            {date}
                        </div>
                        <div className='space' style={{width:8,borderRight:'1px solid hsla(0,0%,59.2%,.2)',height:14}}>

                        </div>
                        <div className='space' style={{width:7,height:22}}>

                        </div>
                        <div className='tagList' style={{display:'flex',alignItems:'center'}}>
                            <div className='tag' style={{fontSize:'13px',height:22,lineHeight:'22px',color:'#86909c'}}>
                                {info.category.category_name?info.category.category_name:'前端'}
                            </div>
                            {/* <div style={{width:17,height:22,display:'flex',alignItems:'center',justifyContent:'center'}}>
                                <div className='point' style={{height:2,width:2,borderRadius:'100%',backgroundColor:'#4e5969'}}/>
                            </div>
                            <div className='tag' style={{fontSize:'13px',height:22,lineHeight:'22px',color:'#86909c'}}>
                                {info.category_info.second_category_name?info.category_info.second_category_name:"React Native"}
                            </div>
                            <div style={{width:17,height:22,display:'flex',alignItems:'center',justifyContent:'center'}}>
                                <div className='point' style={{height:2,width:2,borderRadius:'100%',backgroundColor:'#4e5969'}}/>
                            </div>
                            <div className='tag' style={{fontSize:'13px',height:22,lineHeight:'22px',color:'#86909c'}}>
                                架构
                            </div> */}
                        </div>
                    </div>
                    <div className='content' style={{width:335,height:107,display:'flex',flexWrap:'wrap'}}>
                        <div className='spaceTop' style={{width:335,height:10}}>

                        </div>
                        <div className='infoAndPic' style={{width:335,height:84,display:'flex'}}>
                            <div className='info' style={{width:191,height:84}}>
                                <div className='title' style={{width:176,height:24,fontSize:'16px',color:'#1d2129',overflow:'hidden',textOverflow:"ellipsis",fontWeight:'700',lineHeight:'24px',whiteSpace:'nowrap'}}>
                                    {info.article_info.title?info.article_info.title:"每个前端都值得拥有自己的组件库，就像每个夏天都拥有西瓜🍉"}
                                </div>
                                <div className='space' style={{height:8,width:191}}>

                                </div>
                                <div className='content' style={{height:22,width:176,color:'#86909c',fontWeight:'400',overflow:'hidden',whiteSpace:'nowrap',textOverflow:"ellipsis",fontSize:'13px',lineHeight:'22px'}}>
                                    {info.article_info.brief_content?info.article_info.brief_content:"这是一篇干货比较多的组件库搭建实战教程，不仅有通用的代码规范、提交规范、文档维护、单元测试、GitHub Action 配置的讲解，还涉及基于 lerna 的多包管理架构..."}
                                </div>
                                <div className='space' style={{height:10,width:191}}>

                                </div>
                                <div className='buttonList' style={{height:20,width:191,display:'flex',alignItems:'center',flexWrap:'wrap'}}>
                                    <div className='view' style={{height:20,width:60,display:'flex',flexWrap:'wrap',alignItems:'center'}}>
                                        <img className='viewPic' src={viewSrc} height='16' width='16' alt='1'></img>
                                        <div className='space' style={{width:4,hangingPunctuation:20}}>

                                        </div>
                                        <div className='viewData' style={{fontSize:'13px',lineHeight:'20px',color:'#4e5969'}}>
                                            {info.article_info.view_count>10000?(info.article_info.view_count/10000).toFixed(1)+'w':info.article_info.view_count}
                                        </div>
                                    </div>
                                    <div className='like' style={{height:20,width:60,display:'flex',flexWrap:'wrap',alignItems:'center'}}>
                                        <img className='likePic' alt='' height='16' width='16' src={likeSrc}></img>
                                        <div className='space' style={{width:4,hangingPunctuation:20}}>

                                        </div>
                                        <div className='likeData' style={{fontSize:'13px',lineHeight:'20px',color:'#4e5969'}}>
                                            {info.article_info.collect_count===null?info.article_info.collect_count:info.article_info.collect_count}
                                        </div>
                                    </div>
                                    <div className='comment' style={{height:20,width:60,display:'flex',flexWrap:'wrap',alignItems:'center'}}>
                                        <img alt='' className='commentPic' height='16' width='16' src={commentSrc}></img>
                                        <div className='space' style={{width:4,hangingPunctuation:20}}>

                                        </div>
                                        <div className='commentData' style={{fontSize:'13px',lineHeight:'20px',color:'#4e5969'}}>
                                            {info.article_info.comment_count===null?info.article_info.comment_count:info.article_info.comment_count}
                                        </div>      
                                    </div>
                                </div>
                            </div>
                            <div className='space' style={{width:24,height:84}}>

                            </div>
                            <div className='pic' style={{width:120,height:84}}>
                                <img alt='a' src={picSrc} style={{objectFit:'cover',width:120,height:80}}></img>
                            </div>
                        </div>
                        <div className='spaceBottom' style={{height:12,width:335,borderBottom:'1px solid hsla(0,0%,59.2%,.2)'}}>

                        </div>
                    </div>
                </div>
                <div className='space' style={{width:20,height:141}}>

                </div>
            </div>
        </div>
    )
    
}
function SearchUserBox({brief:props}){
    
    const info = props.result_model
    const pic = info.avatar_large?info.avatar_large:''
    return(
        <div>
            <div className='userBox' style={{boxSizing:'border-box',padding:'24px',width:'100%',height:93,display:'flex'}}>
                <div className='userPic' style={{flexGrow:'0',height:45,marginRight:12}}>
                    <img alt={pic} src={pic} className='avatar' style={{width:45,height:45,borderRadius:'50%',marginTop:5}}></img>
                </div>
                <div className='userInfo' style={{flexGrow:'1',height:45,display:'flex',flexWrap:'wrap'}}>
                    <div className='userName' style={{height:25,fontSize:"16px",lineHeight:'25px',width:'100%',fontWeight:'700',marginBottom:5}}>
                        {info?info.user_name:''}
                    </div>
                    <div className='userBar' style={{height:15,fontSize:'14px',lineHeight:'15px',width:'100%',display:'flex',alignItems:'center',textAlign:'center'}}>
                        <div className='userFollow' >
                            {info.followee_count>10000?(info.followee_count/10000).toFixed(1)+' w关注':info.followee_count+' 关注'}
                        </div>
                        <div style={{width:17,height:22,display:'flex',alignItems:'center',justifyContent:'center'}}>
                            <div className='point' style={{height:2,width:2,borderRadius:'100%',backgroundColor:'#4e5969'}}/>
                        </div>
                        <div className='userLike'>
                            {info.got_digg_count>10000?(info.got_digg_count/10000).toFixed(1)+' w点赞':info.got_digg_count+' 点赞'}
                        </div>
                    </div>
                </div>
                <div className='followButton' style={{flexGrow:'0',height:45,}}>
                    <button  style={{width:55,height:26,marginTop:10,border:'1px solid #6cbd45',color:'#6cbd45',fontSize:'13px',backgroundColor:'#fff'}}>关注</button>
                </div>
            </div>
        </div>
    )
}

function SearchList(){

    return(
        <div>
            <SearchListForArticleAndNew />
            <SearchListForArticleAndHot />
            <SearchListForUser />
        </div>
    )
}

function SearchListForUser(){//id_type=1
    const {state,search} =useContext(SetType)
    const [data,setData] = useState(null)
    const [cursor,setCursor] = useState('0')
    const [id_type,setId_type] = useState()
    const [key_word,setKey_word] = useState()
    useMemo(()=>{
        setKey_word(search)
        setCursor('0')
    },[search])
    useEffect(()=>{
        setId_type(state.id_type)
    },[state])
    useEffect(()=>{
        async function init(){
            const data = await axios.post('https://qc6d2t.fn.thelarkcloud.com/getSearchInfo',{key_word:key_word,cursor:cursor,id_type:1}).catch(error=>console.log(error))
            setData(data.data.result.data)
            // setData(data.data.data.result)
            setCursor(data.data.result.cursor)
            setId_type(state.id_type)
        }
        if(cursor==='0')
            {init()}
    },[search,key_word,cursor,state.id_type])
    useEffect(()=>{
        async function getUser(){
            const data = await axios.post('https://qc6d2t.fn.thelarkcloud.com/getSearchInfo',{key_word:key_word,cursor:cursor,id_type:1}).catch(error=>console.log(error))
            setData(e=>e.concat(data.data.result.data))
            setCursor(data.data.result.cursor)
        }
        const user = document.getElementsByClassName('searchListForUser')[0]
        const handleScroll=()=>{
            // console.log(user.scrollTop)
            // console.log(user.scrollHeight)
            if(user.scrollTop===user.scrollHeight-812)
                getUser()
        }
        user.addEventListener('scroll',handleScroll)
        return()=>{
            user.removeEventListener('scroll',handleScroll)
        }
    },[search,key_word,cursor,state.id_type])
    return(
        <div className='searchListForUser' style={{height:702,backgroundColor:'#fff',paddingTop:'110px',display:id_type==='user'?'':'none',overflow:'scroll'}}>
                <div className='space' style={{height:10,backgroundColor:'#f4f5f5'}}>

                </div>
                {data?data.map((i,index)=>{
                    
                    return <div key={index}>
                        {/* {console.log(i)} */}
                        <SearchUserBox brief={i}/>
                    </div>
                    }):''
                }
                <div className='space' style={{height:50,width:375}}>

                </div>
                {/* <SearchBox brief={data[0]}/> */}
            </div>
    )
}
function SearchListForArticleAndNew(){//id_type=2&&sort_type=1
    const {state,search} =useContext(SetType)
    const [data1,setData1] = useState(null)
    const [cursor,setCursor] = useState("0")
    const [id_type,setId_type] = useState()
    const [sort_type,setSort_type] = useState()
    const [key_word,setKey_word] = useState()
    useMemo(()=>{
        setKey_word(search)
        setCursor('0')
    },[search])
    useEffect(()=>{
        setId_type(state.id_type)
        setSort_type(state.sort_type)
    },[state])
    useEffect(()=>{
        
        async function init(){
            const data = await axios.post('https://qc6d2t.fn.thelarkcloud.com/getSearchInfo',{key_word:key_word,cursor:cursor,id_type:2,sort_type:1}).catch(error=>console.log(error))
            setData1(data.data.result.data)
            setCursor(data.data.result.cursor)
            setId_type(state.id_type)

        }
        if(cursor==="0")
            {init();}

    },[search,key_word,cursor,state.id_type])
    useEffect(()=>{
        async function getMore(){
            const data = await axios.post('https://qc6d2t.fn.thelarkcloud.com/getSearchInfo',{key_word:key_word,cursor:cursor,id_type:2,sort_type:1}).catch(error=>console.log(error))
            setData1(e=>e.concat(data.data.result.data))
            setCursor(data.data.result.cursor)
        }
        const newList = document.getElementsByClassName('searchListForNew')[0]
        const handleScroll=()=>{
            // console.log(newList.scrollTop)
            // console.log(newList.scrollHeight)
            if(newList.scrollTop===newList.scrollHeight-812)
                getMore()
                // console.log(1)
        }
        newList.addEventListener('scroll',handleScroll)
        return()=>{
            newList.removeEventListener('scroll',handleScroll)
        }
    },[search,key_word,cursor,state.id_type]) 
    return(
        <div className='searchListForNew' style={{height:702,backgroundColor:'#fff',paddingTop:'110px',display:id_type==='article'&&sort_type==='new'?'':'none',overflow:'scroll'}}>
                <div className='space' style={{height:10,backgroundColor:'#f4f5f5'}}>

                </div>
                {data1?data1.map((i,index)=>{

                    return <div key={index}>
                        <SearchArticleBox brief={i}/>
                        {/* {console.log(i)} */}
                    </div>
                }):''
                }
                <div className='space' style={{height:50,width:375}}>

                </div>
                {/* <SearchBox brief={data[0]}/> */}
            </div>
    )
}
function SearchListForArticleAndHot(){//id_type=2&&sort_type=2
    const {state,search} =useContext(SetType)
    const [data1,setData1] = useState(null)
    const [cursor,setCursor] = useState("0")
    const [id_type,setId_type] = useState()
    const [sort_type,setSort_type] = useState()
    const [key_word,setKey_word] = useState()
    useMemo(()=>{
        setKey_word(search)
        setCursor('0')
    },[search])
    useEffect(()=>{
        setId_type(state.id_type)
        setSort_type(state.sort_type)
    },[state])
    useEffect(()=>{
        async function init(){
            const data = await axios.post('https://qc6d2t.fn.thelarkcloud.com/getSearchInfo',{key_word:key_word,cursor:cursor,id_type:2,sort_type:2}).catch(error=>console.log(error))
            setData1(data.data.result.data)
            setCursor(data.data.result.cursor)
            setId_type(state.id_type)
        }
        if(cursor==="0")
            {init()}
    },[search,key_word,cursor,state.id_type])
    useEffect(()=>{
        async function getMore(){
            const data = await axios.post('https://qc6d2t.fn.thelarkcloud.com/getSearchInfo',{key_word:key_word,cursor:cursor,id_type:2,sort_type:2}).catch(error=>console.log(error))
            setData1(e=>e.concat(data.data.result.data))
            setCursor(data.data.result.cursor)
        }
        const hotList = document.getElementsByClassName('searchListForHot')[0]
        const handleScroll=()=>{
            // console.log(hotList.scrollTop)
            // console.log(hotList.scrollHeight)
            if(hotList.scrollTop===hotList.scrollHeight-812)
                getMore()
        }
        hotList.addEventListener('scroll',handleScroll)
        return()=>{
            hotList.removeEventListener('scroll',handleScroll)
        }
    },[search,key_word,cursor,state.id_type]) 
    return(
        <div className='searchListForHot' style={{height:702,backgroundColor:'#fff',paddingTop:'110px',display:id_type==='article'&&sort_type==='hot'?'':'none',overflow:'scroll'}}>
                <div className='space' style={{height:10,backgroundColor:'#f4f5f5'}}>

                </div>
                {data1?data1.map((i,index)=>{

                    return <div key={index}>
                        <SearchArticleBox brief={i}/>
                        {/* {console.log(i)} */}
                    </div>
                }):''
                }
                <div className='space' style={{height:50,width:375}}>

                </div>
                {/* <SearchBox brief={data[0]}/> */}
            </div>
    )
}

const SetType = createContext({})
export function Search(){
    // let type ={id_type:'article',sort_type:'hot'}
    const reducer = (state,action)=>{
        const {id_type,sort_type} = state
        switch(action.type)
        {
            case 'user':return {id_type:'user',sort_type:sort_type}
            case 'article': return {id_type:'article',sort_type:sort_type}
            case 'new':return {id_type:id_type,sort_type:'new'}
            case 'hot': return {id_type:id_type,sort_type:'hot'}
            default: return state
        }
    }
    const [state,dispatch] = useReducer(reducer,{id_type:'article',sort_type:'hot'})
    const history = useHistory()
    // console.log(history)
    const search = history.location.query
    return(
        <div>
            <SetType.Provider value={{state,dispatch,search}}>
                <MainHead/>
                <SearchBar/>
                <SearchList/>
                <SearchBottom/>
            </SetType.Provider>
        </div>
    )
}